package com.demo.sso.reids;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 请添加模块注释
 *
 * @author fengjy
 * @date 2018-10-28 23:15
 */

@Configuration
@Data
public class RedisManager {

    private  Logger logger = LoggerFactory.getLogger(RedisManager.class);

    @Autowired
    private  RedisTemplate redisTemplate;

    /**
     * 给Redis中Set集合中某个key值设值
     *
     * @param key
     * @param value
     */
    public  void set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            logger.error("redisTemplate add 异常 [{}]", e);
        }
    }


    /**
     * 从Redis中Set集合中获取key对应value值
     *
     * @param key
     */
    public  Object get(String key) {
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            logger.error("redisTemplate get 异常 [{}]", e);
            return null;
        }
    }


    /**
     * 给Redis中Set集合中某个key值设值
     *
     * @param key
     * @param value
     */
    public  void set(String key, String value, long time) {
        try {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            logger.error("redisTemplate set 异常 [{}]", e);
        }
    }


    /**
     * @return Boolean    成功 返回 true
     * @throws
     * @Title: expire
     * @Description: 设置指定key的生存时间
     */
    public  boolean expire(String key, int seconds) {
        try {
            return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("redisTemplate expire 异常 [{}]", e);
            return false;
        }
    }

    /**
     * @return Boolean    成功 返回 true
     * @throws
     * @Title: expire
     * @Description: 设置指定key的生存时间
     */
    public  long ttl(String key) {
        try {
            return redisTemplate.getExpire(key);
        } catch (Exception e) {
            logger.error("redisTemplate ttl 异常 [{}]", e);
            return 0L;
        }
    }

    /**
     * @return Boolean    返回类型
     * @throws
     * @Title: exist
     * @Description: 判断key是否存在
     */
    public  Boolean exist(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            logger.error("redisTemplate exist 异常 [{}]", e);
            return false;
        }
    }

}
